package ui.operator;

import ent.Employee;
import ent.Operator;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import util.Combo;
import util.SuperView;

/**
 *
 * @author t
 */
public class OperatorView extends SuperView {

    private static OperatorView instance = new OperatorView();

    public static void display() {
        instance.setVisible(true);
    }

    public static OperatorView getInstance() {
        return instance;
    }

    public OperatorView() {
        onLoad();
    }

    /**
     * Creates new form CustomerView
     */
    public OperatorView(java.awt.Frame parent, boolean modal) {
        this();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        employeeComboBox = new javax.swing.JComboBox();
        usernameTextField = new javax.swing.JTextField();
        PasswordField = new javax.swing.JPasswordField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tempTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("OPERATOR MANAGEMENT");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        employeeComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                employeeComboBoxActionPerformed(evt);
            }
        });
        employeeComboBox.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                employeeComboBoxKeyPressed(evt);
            }
        });

        usernameTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usernameTextFieldActionPerformed(evt);
            }
        });

        PasswordField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PasswordFieldActionPerformed(evt);
            }
        });

        tempTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Username", "Created Date", "Created By"
            }
        ));
        tempTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tempTableKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tempTable);

        jLabel1.setText("Employee:");

        jLabel2.setText("Username:");

        jLabel3.setText("Password:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 518, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(employeeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(employeeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void employeeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_employeeComboBoxActionPerformed
        //        if (entities.Employee.isDescription()) {
        //            setDataLable(employeeComboBox, ((entities.Employee) employeeComboBox.getSelectedItem()).getCode());
        //        } else {
        //            setDataLable(employeeComboBox, ((entities.Employee) employeeComboBox.getSelectedItem()).getName());
        //        }
}//GEN-LAST:event_employeeComboBoxActionPerformed

    private void employeeComboBoxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_employeeComboBoxKeyPressed
        if (evt.getKeyCode() == 10) {
            usernameTextField.requestFocus();
        }
}//GEN-LAST:event_employeeComboBoxKeyPressed

    private void usernameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usernameTextFieldActionPerformed
        PasswordField.requestFocus();
}//GEN-LAST:event_usernameTextFieldActionPerformed

    private void PasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PasswordFieldActionPerformed
        createOperator();
}//GEN-LAST:event_PasswordFieldActionPerformed

    private void tempTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tempTableKeyReleased
        if (tempTable.getSelectedRow() != -1 && evt.getKeyCode() == 123) {
            removeRows();
        }
}//GEN-LAST:event_tempTableKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                OperatorView dialog = new OperatorView(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPasswordField PasswordField;
    public static javax.swing.JComboBox employeeComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tempTable;
    private javax.swing.JTextField usernameTextField;
    // End of variables declaration//GEN-END:variables
    DefaultTableModel tempTableModel;

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        Combo.fillEmployees(employeeComboBox);
        fillTempTable();
    }

    protected void onLoad() {
        initComponents();
        tempTableModel = (DefaultTableModel) tempTable.getModel();
    }

    private void removeRows() {
        int[] selected = tempTable.getSelectedRows();
        if (selected.length == tempTable.getRowCount()) {
            showError("You can't delete all operators");
            return;
        }
        for (int idx = 0; idx < selected.length; idx++) {
            if (!m.delete(Operator.class, tempTable.getValueAt(selected[idx], 1).toString())) {
                continue;
            }
        }
        fillTempTable();
    }

    private void createOperator() {
        Object o = employeeComboBox.getSelectedItem();
        if (o instanceof Employee) {
            Employee employee = (Employee) o;
            Collection<Operator> operators = employee.getOperatorCollection();
            if (operators.isEmpty()) {
                String username = usernameTextField.getText().trim();
                String password = new String(PasswordField.getPassword()).trim();
                if (password.equals("") || username.equals("")) {
                    return;
                }
                Operator operator = new Operator(username);
                operator.setCreatedBy(util.Data.getOperator().getUsername());
                operator.setEmployee(employee);
                operator.setUsername(username);
                operator.setPassword(password);
                operator.setPower(0);
                operator.setCreatedDate(new Date());
                m.update(operator);
                fillTempTable();
                usernameTextField.setText("");
                PasswordField.setText("");
                employeeComboBox.requestFocus();
            } else {
                showError("This Employee Is Already an Operator");
            }
        }
    }

    void fillTempTable() {
        tempTableModel.setRowCount(0);
        List<Operator> operators = m.find(Operator.class);
        for (Iterator<Operator> it = operators.iterator(); it.hasNext();) {
            Operator operator = it.next();
            Date cDat = operator.getCreatedDate() == null ? new Date() : operator.getCreatedDate();
            Object[] row = {operator.getEmployee().getFirstName(), operator.getUsername(), yyyy_MM_dd.format(cDat), operator.getCreatedBy()};
            tempTableModel.addRow(row);
        }
    }
}
